package com.kaizzi.data.ppt;

import com.fasterxml.jackson.databind.JsonNode;
import com.kaizzi.data.common.utils.JsonUtil;
import com.kaizzi.data.common.utils.StringUtil;
import com.kaizzi.data.jdl.helper.LocalPageData;
import com.kaizzi.data.jdl.service.JdlDataService;
import com.kaizzi.data.jdl.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.sl.usermodel.TableShape;
import org.apache.poi.sl.usermodel.TextShape;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.*;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author Kzen
 * @Description description
 * @date 2020/9/27
 */
@Component
@Slf4j
public class CreateJdlPPT {

    @Resource
    private JdlDataService jdlDataService;
    @Resource
    private JdlReplaceData jdlReplaceData;
    @Resource
    private LocalPageData localPageData;
    @Resource
    private LogService logService;

    //创建ppt环节 改为数据接口形成后直接生成ppt，保持最新接口一致情况，下载按钮点击后 直接下载最新文件即可
    public void createPPT(String fileName,String templateName){
        logService.setDataLogStatus("ppt-exe");
        //首先判断数据接口是否全部生成成功（数据日期按上周末日期统计）
        try {
//            String fileName = "test.pptx";
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);

            InputStream inputStream = readTemplateInput(templateName);
            XMLSlideShow xmlSlideShow = convertPPtx(inputStream);
            XMLSlideShow xmlSlideShow1 = analysePPTX(xmlSlideShow);
            xmlSlideShow1.write(fileOutputStream);
            xmlSlideShow1.close();
            xmlSlideShow.close();
            inputStream.close();
            fileOutputStream.close();
            logService.recordLog("success",1);
            log.info("JDL-PPT文件创建完成");
            logService.setDataLogStatus("ppt-success");
        } catch (Exception e) {
            logService.setDataLogStatus("ppt-error");
            logService.recordLog("fail",1);
            log.error("page:{}JDL-PPT生成失败，失败原因:{}","",e);
        }
    }

    //具体分析文件流ppt
    private XMLSlideShow analysePPTX(XMLSlideShow xmlSlideShow) {

        List<XSLFSlide> slides = xmlSlideShow.getSlides();
        for (int page = 0; page < slides.size(); page++) {
            //单页调试
            if (getJdlUnchangedPage().contains(page+1)){
                continue;
            }
            // 单页调试使用
//            if (page+1 != 11){
//                continue;
//            }
            //获取指定页ppt
            XSLFSlide slide = slides.get(page);
            log.info("当前PPT页码:{}",page+1);
            //按现在页码 获取原页码
            int oldPage = getOldPage(page);
            //page data
            JsonNode pageData = getPageData(oldPage+1);
            System.out.println(JsonUtil.serialize(pageData));
            //获取当页ppt内形状
            List<XSLFShape> shapes = slide.getShapes();

            //文字替换
            for (XSLFShape shape : shapes) {
                if (shape instanceof XSLFGroupShape){
                    XSLFGroupShape groupShape = (XSLFGroupShape)shape;
                    List<XSLFShape> shapes1 = groupShape.getShapes();
                    for (XSLFShape shape1:shapes1) {
                        if (shape1 instanceof TextShape){
                            List<XSLFTextParagraph> textParagraphs = ((TextShape) shape1).getTextParagraphs();
                            jdlReplaceData.replaceText(oldPage,textParagraphs,pageData);
                        }
                    }
                }
                //文字
                if(shape instanceof TextShape){
                    List<XSLFTextParagraph> textParagraphs = ((TextShape) shape).getTextParagraphs();
                    //修改文字
                    jdlReplaceData.replaceText(oldPage,textParagraphs,pageData);
                }

                //箭头
                if (shape instanceof XSLFSimpleShape){
                    Color fillColor = ((XSLFSimpleShape) shape).getFillColor();
                    if (fillColor == null){
                        continue;
                    }
                    //根据颜色获取trend
                    int red = fillColor.getRed();
                    jdlReplaceData.replaceSimpleShape(oldPage,red,shape,pageData);
                }

                //图表数据
                if (shape instanceof TableShape){
                    jdlReplaceData.replaceTable(oldPage,shape,pageData,slide);
                }
            }

            try {
                //图表
                List<POIXMLDocumentPart.RelationPart> relationParts = slide.getRelationParts();
                for (POIXMLDocumentPart.RelationPart part:relationParts) {
                    POIXMLDocumentPart documentPart = part.getDocumentPart();
                    if (documentPart instanceof XSLFChart) {
                        XSLFChart chart = (XSLFChart) documentPart;
                        //查看图表内数据，
                        CTPlotArea plot = chart.getCTChart().getPlotArea();
                        //图表内数据需要进行更换

                        XSSFWorkbook workbook = chart.getWorkbook();
                        XSSFSheet sheet = workbook.getSheetAt(0);

                        if (!plot.getBarChartList().isEmpty()){
                            jdlReplaceData.replaceBarChart(oldPage,plot,pageData,workbook,sheet,chart);
                        }
                        if (!plot.getLineChartList().isEmpty()){
                            jdlReplaceData.replaceLineChart(oldPage,plot,pageData,workbook,sheet,chart);
                        }
                        if (!plot.getPieChartList().isEmpty()){
                            jdlReplaceData.replacePieChart(oldPage,plot,pageData,workbook,sheet,chart);
                        }
                    }
                }
            }catch (Exception e){
                logService.setDataLogStatus("ppt-error");
                log.error("page:{},图表数据转换异常,异常原因:{}",oldPage+1,e);
            }
        }
        return xmlSlideShow;
    }

    private int getOldPage(int page) {
        switch (page){
            case 0:
                return 0;
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 3;
            case 4:
                return 4;
            case 7:
                return 6;
            case 8:
                return 7;
            case 9:
                return 8;
            case 10:
                return 9;
            case 11:
                return 10;
            case 12:
                return 11;
            case 13:
                return 12;
            case 14:
                return 13;
            case 15:
                return 14;
//            case 16:
//                return 16;
//            case 17:
//                return 19;
//            case 18:
//                return 20;
//            case 19:
//                return 21;
            case 20:
                return 23;
            case 21:
                return 24;
            case 22:
                return 26;
            case 23:
                return 28;
            case 24:
                return 29;
            case 25:
                return 31;
            case 26:
                return 33;
            case 27:
                return 34;
            case 29:
                return 36;
            case 30:
                return 37;
            case 31:
                return 38;
            case 32:
                return 40;
            case 33:
                return 41;
            case 34:
                return 42;
            case 35:
                return 44;
            case 36:
                return 45;
            default:
                return 100;
        }
    }


    //读取ppt文件流
    private InputStream readTemplateInput(String templateName) throws Exception {
        //模板ppt名称
        return new FileInputStream(new File(templateName));
    }

    //将文件流转为ppt
    private XMLSlideShow convertPPtx(InputStream inputStream) throws IOException {
        return new XMLSlideShow(inputStream);
    }

    //数据转为json
    private JsonNode getPageData(int page){
//        if (getJdlUnchangedPage().contains(page)){
//            return null;
//        }
        try {
            JsonNode jsonNode = JsonUtil.deserialize(jdlDataService.getPageData(StringUtil.join(page)));
            log.info("页面数据获取成功，页码:{},数据:{}",page,jsonNode);
            return jsonNode;
        }catch (Exception e){
            return null;
        }
    }

    //数据获取暂时取本地数据 临时使用
    private JsonNode getPageDataTemp(int page){
        //仅支持单页调试使用
        return JsonUtil.deserialize(localPageData.getPageData(page));
    }

    //jdl固定不改变页面
    private List<Integer> getJdlUnchangedPage(){
        //固定不改变页面
        return Arrays.asList(2,3,5,6,7,14,16,17,18,19,20,35);
    }

//    private void recordLog(String status) {
//        LogHistory logHistory = new LogHistory();
//        logHistory.setProjectName("jdl");
//        logHistory.setCategory("ppt");
//        logHistory.setStatus(status);
//        logHistory.setCreateTime(DateUtil.getDateTimeNow());
//        logService.save(logHistory);
//    }
}
